﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Consulta.Manager;
using Consulta.Core;
using System.IO;
using System.Data;

public partial class Pages_DetPago : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            if (User.IsInRole(@"COSTARICA\CR_Intranet_Financiero.R") || User.IsInRole(@"GRUPOBANACOL\CR_Intranet_Financiero.R"))
            {
                if (Page.Request.QueryString.Count > 0)
                {
                    Label lblTituloMaster = new Label();
                    lblTituloMaster = (Label)this.Form.Parent.FindControl("lblTitulo");
                    lblTituloMaster.Text = "Intranet-Consulta de Pagos a Proveedores";
                    int tNumeEgre = int.Parse(Page.Request.QueryString["Egreso"]);
                    lblEgreso.Text = tNumeEgre.ToString();
                    string tCia = Page.Request.QueryString["Cia"];
                    string tLibDatos = "";
                    switch (tCia)
                    {
                        case "BAC":
                            tLibDatos = "CPXDTCRP";
                            lblCia.Text = "Comercializadora Bananeros de Costa Rica S.A.";
                            break;
                        case "TER":
                            tLibDatos = "CPXDTTEP";
                            lblCia.Text = "Cia Bananera La Teresa S.A.";
                            break;
                        case "AGC":
                            tLibDatos = "CPXDTAGC";
                            lblCia.Text = "Agricola Ganadera Cariari S.A.";
                            break;
                        case "FTV":
                            tLibDatos = "CPXDTFTV";
                            lblCia.Text = "Frutas Tropicales Venecia S.A.";
                            break;
                        case "INC":
                            tLibDatos = "CPXDTINC";
                            lblCia.Text = "Industria Cartonera INCA S.A.";
                            break;
                        case "CAY":
                            tLibDatos = "CPXDTCAY";
                            lblCia.Text = "Agricola Industrial San Cayetano S.A.";
                            break;
                        case "BAN":
                            tLibDatos = "CPXDTBAN";
                            lblCia.Text = "Banacol de Costa Rica S.A.";
                            break;
                    }
                    //Leer datos del egreso
                    Egreso tEgreso = new Egreso();
                    MTesoreria tMEgreso = new MTesoreria();
                    tEgreso = tMEgreso.consultarID(tLibDatos, tNumeEgre);
                    //Asignar valores a la forma
                    lblEgreso.Text = tEgreso.EgrCmp.ToString();
                    lblCuenta.Text = tEgreso.EgrCta;
                    lblNumePago.Text = tEgreso.EgrNdc;
                    lblBeneficiario.Text = tEgreso.EgrDsn;
                    lblFecha.Text = tEgreso.EgrFch;
                    lblConcepto.Text = tEgreso.EgrCon;
                    lblLibDatos.Text = tLibDatos;
                    //Asignar tipo de pago
                    if (tEgreso.EgrTipPag == "C")
                    {
                        lblTipoPago.Text = "Cheque";
                    }
                    else if (tEgreso.EgrTipPag == "N")
                    {
                        lblTipoPago.Text = "Nota";
                    }
                    else if (tEgreso.EgrTipPag == "T")
                    {
                        lblTipoPago.Text = "Transferencia";
                    }
                    //Total del pago y moneda
                    lblTotaPago.Text = tEgreso.EgrVnt.ToString("n");
                    if (tEgreso.EgrMon == "US")
                    {
                        lblMoneda.Text = "Dolares";
                    }
                    else
                    {
                        lblMoneda.Text = "Colones";
                    }
                }
            }
            else
            {
                Response.Redirect("~/Pages/PaginaMensaje.aspx?Msj=Lo sentimos. Usted no tiene autorización para ingresar a esta página.");
            }
        }
    }
    protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Header)
        {
            //Cambiar titulo de columnas dependiendo del concepto
            if (lblConcepto.Text == "PGD")
            {
                e.Row.Cells[0].Text = "Concepto";
                e.Row.Cells[1].Text = "Numero";
                e.Row.Cells[4].Text = "Valor Col";
            }
            else if (lblConcepto.Text == "ANT")
            {
                e.Row.Cells[0].Text = "Anticipo";
                e.Row.Cells[1].Text = "Factura";
                e.Row.Cells[4].Text = "Legalizado";
                e.Row.Cells[5].Text = "Obligacion";

            }
            else 
            {
                //Pago por cualquier concepto por CXP
                e.Row.Cells[0].Text = "Tipo";
                e.Row.Cells[1].Text = "Factura";
                e.Row.Cells[4].Text = "Valor Pago";
                e.Row.Cells[5].Text = "Obligacion";
            }

        }
    }

    protected void lnkExcel_Click(object sender, EventArgs e)
    {
        try
        {
            //Buscar grid del content page
            if (GridView1.Rows.Count > 0)
            {
                GridView1.AllowPaging = false;
                GridView1.DataBind();
                Export("Consultas Intranet.xls", GridView1);
            }
        }
        catch (Exception ex)
        {

            throw new Exception("error al exportar a excel. " + ex.Message);
        }
    }
    protected void Export(string fileName, GridView gv)
    {
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", fileName));
        HttpContext.Current.Response.ContentType = "application/ms-excel";

        StringWriter sw = new StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(sw);
        //  Create a form to contain the grid
        Table table = new Table();
        DataTable t = new DataTable();

        TableRow tFila = new TableRow();
        TableCell tCelda = new TableCell();
        //Adicionar filas de encabezado al archivo de Excel
        tCelda.Text = "Consultas Intranet de Costa Rica";
        tFila.Cells.Add(tCelda);
        table.Rows.Add(tFila);
        //tCelda.Text = lblTitulo.Text;
        tFila.Cells.Add(tCelda);
        table.Rows.Add(tFila);
        //table.BorderWidth = new Unit(1);
        //table.BorderStyle = BorderStyle.Solid;
        table.GridLines = GridLines.Both;

        //  add the header row to the table
        if (gv.HeaderRow != null)
        {
            PrepareControlForExport(gv.HeaderRow);
            table.Rows.Add(gv.HeaderRow);
        }

        //  add each of the data rows to the table
        foreach (GridViewRow row in gv.Rows)
        {
            PrepareControlForExport(row);
            table.Rows.Add(row);
        }

        //  add the footer row to the table
        if (gv.FooterRow != null)
        {
            PrepareControlForExport(gv.FooterRow);
            table.Rows.Add(gv.FooterRow);
        }

        //  render the table into the htmlwriter
        table.RenderControl(htw);

        //  render the htmlwriter into the response
        HttpContext.Current.Response.Write(sw.ToString());
        HttpContext.Current.Response.End();
    }

    /// <summary>
    /// Replace any of the contained controls with literals
    /// </summary>
    /// <param name="control"></param>
    protected void PrepareControlForExport(Control control)
    {
        for (int i = 0; i < control.Controls.Count; i++)
        {
            Control current = control.Controls[i];
            if (current is LinkButton)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as LinkButton).Text));
            }
            else if (current is ImageButton)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as ImageButton).AlternateText));
            }
            else if (current is HyperLink)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as HyperLink).Text));
            }
            else if (current is DropDownList)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as DropDownList).SelectedItem.Text));
            }
            else if (current is CheckBox)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? "True" : "False"));
            }

            if (current.HasControls())
            {
                PrepareControlForExport(current);
            }
        }
    }

}
